package com.cspg.ssss.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.UUID;
@RestController
@RequestMapping("/scbase")
public class Base64ToImgUtil {
    static BASE64Encoder encoder = new sun.misc.BASE64Encoder();
    static BASE64Decoder decoder = new sun.misc.BASE64Decoder();
    /**
     * 测试base64转图片，并存储到本地
     * @param
     *
     * @return
     */
    @RequestMapping(value = "/scbase", method = RequestMethod.POST)
    public static void test( @RequestBody JSONArray jSONArray ) throws IOException {
        try {
            for(int i=0;i< jSONArray.size();i++) {
                JSONObject oj=jSONArray.getJSONObject(i);
                String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
                String base64=oj.getString("base64");
                String s=base64.substring(base64.indexOf("/")+1,base64.indexOf(";"));
                String base64Data = base64.split(",")[1];
                byte[] bytes1 = decoder.decodeBuffer(base64Data);
                ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
                BufferedImage bi1 = ImageIO.read(bais);
                File f1 = new File("D:\\"+i+"."+s);
                ImageIO.write(bi1, s, f1);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static String getImgStr(String imgFile) throws  Exception{

        InputStream in = null;
        byte[] data = null;
        // 读取图片字节数组
        try {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return encoder.encode(data);
    }
}
